package com.ma.chapter6.logadder;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;

import static com.ma.util.Sleeper.sleep;

/*
 * 使用  CAS+标记位  实现一个  “锁”
 * */
@Slf4j(topic = "m.LockCas")
public class LockCas {
    // 0 没加锁
    // 1 加了锁
    private AtomicInteger state = new AtomicInteger(0);

    public void lock() {
        //会导致不停轮询，不建议生产实践使用
        while (true) {
            if (state.compareAndSet(0, 1)) {
                break;
            }
        }
    }

    public void unlock() {
        log.debug("unlock....");
        state.set(0);
    }

    public static void main(String[] args) {
        LockCas lock = new LockCas();
        new Thread(() -> {
            log.debug("begin");
            lock.lock();
            try {
                log.debug("lock");
                sleep(1);
            } finally {
                lock.unlock();
            }
        }, "t1").start();

        new Thread(() -> {
            log.debug("begin");
            lock.lock();
            try {
                log.debug("lock");
            } finally {
                lock.unlock();
            }
        }, "t2").start();


    }

}
